package com.wgh.order.service.impl;

import com.wgh.order.entity.Order;
import com.wgh.order.entity.OrderItem;
import com.wgh.order.mapper.OrderMapper;
import com.wgh.order.mapper.OrderItemMapper;
import com.wgh.order.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wgh.common.vo.PageResult;
import com.wgh.api.client.inventory.InventoryClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import io.seata.spring.annotation.GlobalTransactional;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.math.BigDecimal;
import java.util.logging.Logger;
import java.util.logging.Level;

/**
 * 订单服务实现类
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    
    private static final Logger LOGGER = Logger.getLogger(OrderServiceImpl.class.getName());
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderItemMapper orderItemMapper;
    
    // 注入库存服务，使用Spring Cloud Feign
    @Autowired
    private InventoryClient inventoryClient;
    
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @Transactional(rollbackFor = Exception.class)
    public Order createOrder(Order order) {
        try {
            // 1. 生成订单编号
            String orderSn = generateOrderSn();
            order.setOrderSn(orderSn);
            
            // 2. 设置初始状态
            order.setOrderStatus(0); // 待付款
            order.setPayStatus(0);   // 未支付
            order.setCreateTime(LocalDateTime.now());
            order.setTotalAmount(BigDecimal.ZERO);
            
            // 3. 获取订单商品列表
            List<OrderItem> orderItems = order.getOrderItems();
            if (orderItems == null || orderItems.isEmpty()) {
                throw new RuntimeException("订单商品列表不能为空");
            }
            
            // 4. 验证并锁定库存
            Map<Long, Integer> inventoryMap = new HashMap<>();
            for (OrderItem item : orderItems) {
                inventoryMap.put(item.getSkuId(), item.getQuantity());
            }
            boolean lockResult = inventoryClient.deductInventory(inventoryMap);
            if (!lockResult) {
                throw new RuntimeException("库存锁定失败");
            }
            
            // 5. 计算订单总金额
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (OrderItem item : orderItems) {
                // 计算商品总金额
                item.setTotalAmount(item.getPrice().multiply(new BigDecimal(item.getQuantity())));
                totalAmount = totalAmount.add(item.getTotalAmount());
            }
            order.setTotalAmount(totalAmount);
            
            // 6. 保存订单主表
            this.save(order);
            
            // 7. 保存订单商品项
            for (OrderItem item : orderItems) {
                item.setOrderId(order.getId());
                orderItemMapper.insert(item);
            }
            
            LOGGER.info("订单创建成功，订单编号：" + orderSn);
            return order;
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "创建订单失败：" + e.getMessage(), e);
            // 如果出现异常，需要解锁已锁定的库存
            if (order.getOrderItems() != null) {
                for (OrderItem item : order.getOrderItems()) {
                    try {
                        Map<Long, Integer> inventoryMap = new HashMap<>();
                        inventoryMap.put(item.getSkuId(), item.getQuantity());
                        inventoryClient.increaseInventory(inventoryMap);
                    } catch (Exception ex) {
                        LOGGER.log(Level.WARNING, "解锁库存失败：" + ex.getMessage());
                    }
                }
            }
            throw new RuntimeException("创建订单失败：" + e.getMessage());
        }
    }
    
    @Override
    public Order getOrderDetail(Long orderId) {
        return this.getById(orderId);
    }
    
    @Override
    public Order getOrderBySn(String orderSn) {
        return orderMapper.selectByOrderSn(orderSn);
    }
    
    @Override
    public List<Order> getOrdersByUserId(Long userId, Integer orderStatus) {
        return orderMapper.selectByUserIdAndStatus(userId, orderStatus);
    }
    
    @Override
    public PageResult<Order> pageOrders(Map<String, Object> params, Integer pageNum, Integer pageSize) {
        // 这里可以根据MyBatis-Plus的分页功能实现
        // 暂时返回空实现
        return new PageResult<>();
    }
    
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Long orderId, Long userId) {
        try {
            Order order = this.getById(orderId);
            if (order == null || !order.getUserId().equals(userId)) {
                LOGGER.warning("订单不存在或不属于当前用户，无法取消，订单ID：" + orderId);
                return false;
            }
            
            // 只有待付款状态的订单才能取消
            if (order.getOrderStatus() == 0) {
                // 1. 查询订单商品列表
                List<OrderItem> orderItems = orderItemMapper.selectByOrderId(orderId);
                
                // 2. 解锁库存
                if (orderItems != null && !orderItems.isEmpty()) {
                    for (OrderItem item : orderItems) {
                        try {
                        Map<Long, Integer> inventoryMap = new HashMap<>();
                        inventoryMap.put(item.getSkuId(), item.getQuantity());
                        inventoryClient.increaseInventory(inventoryMap);
                        LOGGER.info("订单取消，商品库存已解锁，商品ID：" + item.getProductId() + "，数量：" + item.getQuantity());
                    } catch (Exception ex) {
                        LOGGER.log(Level.WARNING, "订单取消，库存解锁失败：" + ex.getMessage());
                        // 继续处理其他商品，不中断流程
                    }
                    }
                }
                
                // 3. 更新订单状态
                order.setOrderStatus(5); // 已取消
                order.setCancelTime(LocalDateTime.now());
                boolean updateResult = this.updateById(order);
                
                if (updateResult) {
                    LOGGER.info("订单取消成功，订单ID：" + orderId);
                } else {
                    LOGGER.warning("订单取消失败，订单状态更新失败，订单ID：" + orderId);
                }
                
                return updateResult;
            } else {
                LOGGER.warning("订单状态不正确，无法取消，订单ID：" + orderId + "，当前状态：" + order.getOrderStatus());
                return false;
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "取消订单失败：" + e.getMessage(), e);
            throw new RuntimeException("取消订单失败：" + e.getMessage());
        }
    }
    
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(Long orderId, Integer payType, String transactionId) {
        try {
            Order order = this.getById(orderId);
            if (order == null || order.getOrderStatus() != 0) {
                LOGGER.warning("订单不存在或状态不正确，无法支付，订单ID：" + orderId);
                return false;
            }
            
            // 1. 查询订单商品列表
            List<OrderItem> orderItems = orderItemMapper.selectByOrderId(orderId);
            if (orderItems == null || orderItems.isEmpty()) {
                LOGGER.warning("订单商品列表为空，无法支付，订单ID：" + orderId);
                return false;
            }
            
            // 2. 扣减锁定的库存
            Map<Long, Integer> inventoryMap = new HashMap<>();
            for (OrderItem item : orderItems) {
                // 解锁并扣减库存（实际实现可能需要先解锁再扣减，或直接扣减锁定库存）
                inventoryMap.put(item.getSkuId(), item.getQuantity());
            }
            boolean decreaseResult = inventoryClient.deductInventory(inventoryMap);
            if (!decreaseResult) {
                throw new RuntimeException("库存扣减失败");
            }
            
            // 3. 更新订单支付状态
            order.setPayStatus(1); // 已支付
            order.setPayType(payType);
            order.setTransactionId(transactionId);
            order.setPayTime(LocalDateTime.now());
            order.setOrderStatus(1); // 待发货
            
            boolean updateResult = this.updateById(order);
            if (updateResult) {
                LOGGER.info("订单支付成功，订单ID：" + orderId + "，交易流水号：" + transactionId);
            } else {
                LOGGER.warning("订单状态更新失败，订单ID：" + orderId);
            }
            
            return updateResult;
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "订单支付处理失败：" + e.getMessage(), e);
            // 支付异常，可以根据实际情况决定是否需要解锁库存
            throw new RuntimeException("订单支付处理失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmReceipt(Long orderId, Long userId) {
        Order order = this.getById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }
        
        // 只有待收货状态的订单才能确认收货
        if (order.getOrderStatus() == 2) {
            order.setOrderStatus(4); // 已完成
            order.setFinishTime(LocalDateTime.now());
            return this.updateById(order);
        }
        
        return false;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOrder(Long orderId, Long userId) {
        Order order = this.getById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }
        
        // 只有已完成或已取消的订单才能删除
        if (order.getOrderStatus() == 4 || order.getOrderStatus() == 5) {
            return this.removeById(orderId);
        }
        
        return false;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderStatus(Long orderId, Integer orderStatus) {
        return orderMapper.updateOrderStatus(orderId, orderStatus) > 0;
    }
    
    /**
     * 生成订单编号
     * @return 订单编号
     */
    private String generateOrderSn() {
        // 简单实现：时间戳 + 随机数
        return LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) 
                + (int)(Math.random() * 1000);
    }
}